import { useEffect, useState } from 'react'
import meetingApi from '../api/index'
import { useLocation } from 'react-router-dom'
import './index.scss'
import { Button, DatePicker, Flex, Input, Select } from 'antd'
import { MyDrawer } from '@/component/common/myDrawer'
import MyTable from '@/component/common/myTable'
import { MyDialog } from '@/component/common/myDialog'
import { UserArr } from '@/pages/user/interface'
import userApi from '@/pages/user/api'
import RegionSelect from '@/component/common/regionSelect/regionSelect'
import { USER_SEX } from '@/pages/user/config'
import { useMessageApi } from '@/component/context/messageContext/message'
import TableSelects, {
  SelectItem,
} from '@/component/common/tableSelects/tableSelects'
import dayjs from 'dayjs'
import PIcon from '@/component/common/pIcon'
const { RangePicker } = DatePicker
export default function MeetingConf() {
  const location = useLocation()
  const [isShowScorePanel, setIsShowScorePanel] = useState<boolean>(false)
  const [curMeetingData, setCurMeetingData] = useState<any>({})
  const [meetingUsers, setMeetingUsers] = useState<any[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [userSelectedRowKeys, setUserSelectedRowKeys] = useState<number[]>([])
  const messageApi = useMessageApi()
  const [interviewer, setInterviewer] = useState<any[]>([])
  const [userDialog, setUserDialog] = useState<boolean>(false)
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: '',
    phone: '',
    email: '',
    auth: 'user',
  })
  const [interviewSearchParams, setInterviewSearchParams] = useState({
    name: '',
  })
  const [interviewData, setInterviewData] = useState<any[]>([])
  const [scorePanelData, setScorePanelData] = useState<any[]>([])
  const getMeetings = (id: string) => {
    meetingApi.getMeetings({ id }).then((data: any) => {
      setCurMeetingData(data.res)
      setScorePanelData(data.res.score_panel ? JSON.parse(data.res.score_panel) : [])
      setMeetingUsers(data.users)
      const usedUserId = data.users.map((item: any) => {
        return item.id
      })
      setUserSelectedRowKeys(usedUserId)
      setInterviewData(data.interviews)
    })
  }
  const [state, setState] = useState({
    isShowUserManage: false,
  })
  const [userData, setUserData] = useState<UserArr>({
    users: [],
    total: 0,
  })
  // 获取全部用户api
  const getUsers = (params: any) => {
    userApi.getUsers(params).then((res: any) => {
      res.users.forEach((element: any) => {
        element.key = element.id
      })
      setUserData(res)
    })
    let temp = { ...params }
    temp.pageNum = 1
    temp.pageSize = 999
    temp.auth = 'interviewer'
    userApi.getUsers(temp).then((res: any) => {
      res.users.forEach((element: any) => {
        element.value = element.id
        element.label = element.name
      })
      setInterviewer(res.users)
    })
  }

  const updateInterViewTime = async (interview: {
    interviewId: string
    begin: string
    end: string
    interviewer_id?: string
  }) => {
    meetingApi.updateInterViewTime(interview).then((res) => {
      messageApi.success('修改成功')
    })
  }
  useEffect(() => {
    getMeetings(location.pathname.split('/')[4])
    getUsers(searchParams)
  }, [location.pathname])

  // 全部用户Dialog
  const UserDialog = () => {
    const addMeetingUsers = async (
      meetingId: string,
      userIds: Array<number>
    ) => {
      await meetingApi.addMeetingUsers({ meetingId, userIds }).then((res) => {
        messageApi.success('添加成功')
        getMeetings(location.pathname.split('/')[4])
        setUserDialog(false)
      })
    }

    // 用户列表
    const UserTable = () => {
      const rowSelection = {
        selectedRowKeys: userSelectedRowKeys,
        onChange: (selectedRowKeys: any) => {
          setUserSelectedRowKeys(selectedRowKeys)
        },
        getCheckboxProps: (record: any) => ({
          disabled: false,
        }),
      }
      const columns: any = [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
          align: 'center',
          render: (_: any, { sex }: any) => <>{USER_SEX[sex - 1]?.label}</>,
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
          align: 'center',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          align: 'center',
        },
        {
          title: '出生日期',
          dataIndex: 'birth_day',
          key: 'birth_day',
          render: (text: string) => {
            return text?.slice(0, 10)
          },
          align: 'center',
        },
        {
          title: '户籍地区',
          dataIndex: 'home',
          key: 'home',
          align: 'center',
          render: (_: any, { home }: any) => (
            <RegionSelect onlyRead value={home}></RegionSelect>
          ),
        },
      ]
      return (
        <MyTable
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          dataSource={userData?.users}
          columns={columns}
          pageSize={searchParams.pageSize}
          total={userData.total}
          onPaginationChange={(pageNum, pageSize) => {
            setSearchParams((oldV) => {
              return {
                ...oldV,
                pageNum,
                pageSize,
              }
            })
          }}></MyTable>
      )
    }
    // 过滤器组件
    const UserFilter = () => {
      const tableOptions: SelectItem[] = [
        {
          render: (
            <Input
              key="name"
              placeholder="搜索姓名"
              value={searchParams.name}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, name: e.target.value }
                })
              }}
            />
          ),
        },
        {
          render: (
            <Input
              key="phone"
              placeholder="搜索手机号"
              value={searchParams.phone}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, phone: e.target.value }
                })
              }}
            />
          ),
        },
        {
          render: (
            <Input
              key="email"
              placeholder="搜索邮箱"
              value={searchParams.email}
              allowClear
              onChange={(e) => {
                setSearchParams((oldV) => {
                  return { ...oldV, email: e.target.value }
                })
              }}
            />
          ),
        },
      ]
      return (
        <TableSelects
          options={tableOptions}
          source={searchParams}
          onReset={() => {
            setSearchParams({
              pageNum: 1,
              pageSize: 20,
              name: '',
              phone: '',
              email: '',
              auth: 'user',
            })
            getUsers({
              pageNum: 1,
              pageSize: 20,
              name: '',
              phone: '',
              email: '',
            })
          }}
          onSearch={() => {
            getUsers({
              pageNum: searchParams.pageNum,
              pageSize: searchParams.pageSize,
              name: searchParams.name,
              phone: searchParams.phone,
              email: searchParams.email,
            })
          }}></TableSelects>
      )
    }
    return (
      <MyDialog
        width="80%"
        open={userDialog}
        onCancel={() => setUserDialog(false)}
        onClose={() => setUserDialog(false)}
        onOk={() => {
          addMeetingUsers(location.pathname.split('/')[4], userSelectedRowKeys)
        }}>
        <div style={{ height: '60vh' }}>
          {UserFilter()}
          {UserTable()}
        </div>
      </MyDialog>
    )
  }
  // 用户管理抽屉
  const userDrawer = () => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    const userColumns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '操作',
        key: 'action',
      },
    ]
    /**
     * 删除面试用户
     * @param meetingId
     * @param userIds
     */
    const delMeetingUsers = async (
      meetingId: string,
      userIds: Array<number>
    ) => {
      await meetingApi.delMeetingUsers({ meetingId, userIds }).then((res) => {
        messageApi.success('删除成功')
        getMeetings(location.pathname.split('/')[4])
      })
    }
    return (
      <MyDrawer
        open={state.isShowUserManage}
        footer={
          <Flex gap={'1rem'} justify="right">
            {selectedRowKeys.length > 0 && (
              <Button
                onClick={() => {
                  delMeetingUsers(
                    location.pathname.split('/')[4],
                    selectedRowKeys
                  )
                }}>
                删除
              </Button>
            )}
            <Button onClick={() => setUserDialog(true)}>添加面试者</Button>
            <Button
              htmlType="submit"
              onClick={() => {
                setState((oldV) => {
                  return { ...oldV, isShowUserManage: false }
                })
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() => {
          setState((oldV) => {
            return { ...oldV, isShowUserManage: false }
          })
        }}>
        <MyTable
          page={false}
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          dataSource={meetingUsers}
          columns={userColumns}></MyTable>
        {UserDialog()}
      </MyDrawer>
    )
  }

  // 面试列表
  const InterviewList = () => {
    const sendEmail = async (id: string) => {
      await meetingApi
        .sendEmail({
          meetingId: location.pathname.split('/')[4],
          userId: id,
        })
        .then((res: any) => {
          if (res.type === 'success') {
            messageApi.success(res.msg)
          } else {
            messageApi.error(res.msg)
          }
        })
    }
    // 面试列表
    const InterviewTable = () => {
      const columns: any = [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
          render: (_: any, { name, sex }: any) => (
            <>
              {name} ({USER_SEX[sex - 1]?.label})
            </>
          ),
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
          align: 'center',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
          align: 'center',
        },
        {
          title: '面试时间',
          dataIndex: 'begin',
          align: 'center',
          width: 400,
          key: 'begin',
          render: (_: any, { id, begin, end }: any) => {
            if (!begin || !end) {
              return (
                <RangePicker
                  disabledDate={(current: any) => {
                    const customDate = dayjs().subtract(1, 'days')
                    return current && current < customDate
                  }}
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  onChange={(value: any, dateString: any) => {
                    setInterviewData((oldV) => {
                      oldV.forEach((item) => {
                        if (item.id === id) {
                          item.begin = dateString[0]
                          item.end = dateString[1]
                        }
                      })
                      return [...oldV]
                    })
                    updateInterViewTime({
                      interviewId: id,
                      begin: dateString[0],
                      end: dateString[1],
                    })
                  }}
                />
              )
            }
            return (
              <RangePicker
                disabledDate={(current: any) => {
                  const customDate = dayjs().subtract(1, 'days')
                  return current && current < customDate
                }}
                showTime={{ format: 'HH:mm:ss' }}
                format="YYYY-MM-DD HH:mm:ss"
                onChange={(value: any, dateString: any) => {
                  setInterviewData((oldV) => {
                    oldV.forEach((item) => {
                      if (item.id === id) {
                        item.begin = dateString[0]
                        item.end = dateString[1]
                      }
                    })
                    return [...oldV]
                  })
                  updateInterViewTime({
                    interviewId: id,
                    begin: dateString[0],
                    end: dateString[1],
                  })
                }}
                value={[dayjs(begin), dayjs(end)]}
              />
            )
          },
        },
        {
          title: '面试官',
          dataIndex: 'interviewer_id',
          key: 'interviewer_id',
          align: 'center',
          render: (_: any, { id, interviewer_id }: any) => {
            return (
              <Select
                placeholder="请选择"
                value={interviewer_id}
                style={{ width: '100%' }}
                options={interviewer}
                onChange={(value) => {
                  setInterviewData((oldV) => {
                    oldV.forEach((item) => {
                      if (item.id === id) {
                        item.interviewer_id = value
                        updateInterViewTime({
                          interviewId: id,
                          begin: dayjs(item.begin).format(
                            'YYYY-MM-DD HH:mm:ss'
                          ),
                          end: dayjs(item.end).format('YYYY-MM-DD HH:mm:ss'),
                          interviewer_id: value,
                        })
                      }
                    })
                    return [...oldV]
                  })
                }}></Select>
            )
          },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          align: 'center',
          render: (_: any, { user_id, is_send_email }: any) => {
            return (
              <Flex justify="space-around">
                <Button
                  size="small"
                  variant="text"
                  onClick={() => {
                    sendEmail(user_id)
                  }}>
                  {is_send_email ? '再次发送' : '发送邮件'}
                </Button>
              </Flex>
            )
          },
        },
      ]
      return (
        <MyTable
          rowKey={(record) => record.id}
          dataSource={interviewData}
          columns={columns}
          page={false}></MyTable>
      )
    }
    // 过滤器组件
    const InterviewFilter = () => {
      const tableOptions: SelectItem[] = [
        {
          render: (
            <Input
              key="name"
              placeholder="搜索姓名"
              value={interviewSearchParams.name}
              allowClear
              onChange={(e) => {
                setInterviewSearchParams({ name: e.target.value })
              }}
            />
          ),
        },
      ]
      return (
        <TableSelects
          options={tableOptions}
          source={interviewSearchParams}
          onSearch={() => {}}></TableSelects>
      )
    }

    return (
      <div className="interview-list">
        {InterviewFilter()}
        {InterviewTable()}
      </div>
    )
  }

  const updateMeeting = () => {
    let meetDate = {
      id: curMeetingData.id,
      name: curMeetingData.name,
      score_panel: JSON.stringify(scorePanelData),
    }
    meetingApi.updateMeeting(meetDate).then((data) => {
      messageApi.success(data)
      getMeetings(location.pathname.split('/')[4])
    })
  }
  // 用户管理抽屉
  const ScorePanelDrawer = () => {
    return (
      <MyDrawer
        open={isShowScorePanel}
        width="40%"
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button onClick={() => setIsShowScorePanel(false)}>取消</Button>
            <Button
              htmlType="submit"
              onClick={() => {
                updateMeeting()
                setIsShowScorePanel(false)
              }}>
              保存
            </Button>
          </Flex>
        }
        onClose={() => {
          setIsShowScorePanel(false)
        }}>
        <Flex vertical gap={'1rem'}>
          {scorePanelData.map((item, index) => {
            return (
              <Flex align="center" justify="space-around">
                <div>评分标准{index + 1}：</div>
                <Input.TextArea
                  key={index}
                  style={{ width: '80%' }}
                  value={item.desc}
                  onChange={(e) => {
                    setScorePanelData((oldV) => {
                      let temp = [...oldV]
                      temp[index].desc = e.target.value
                      return [...temp]
                    })
                  }}></Input.TextArea>
                <PIcon
                  name="icon-minus-circle"
                  size={20}
                  onClick={() => {
                    setScorePanelData((oldV) => {
                      let temp = [...oldV]
                      temp.splice(index, 1)
                      return [...temp]
                    })
                  }}></PIcon>
              </Flex>
            )
          })}
          <Button
            onClick={() => {
              setScorePanelData((oldV) => {
                return [...oldV, { desc: '' }]
              })
            }}>
            添加
          </Button>
        </Flex>
      </MyDrawer>
    )
  }

  return (
    <div className="meeting-conf">
      <Flex justify="space-between" className="meeting-title">
        <div style={{ width: '20%' }}></div>
        <h2>{curMeetingData.name}</h2>
        <Flex style={{ width: '20%' }} justify="space-around">
          <Button
            onClick={() => {
              setState((oldV) => {
                return {
                  ...oldV,
                  isShowUserManage: true,
                }
              })
            }}>
            面试者管理
          </Button>
          <Button
            onClick={() => {
              setIsShowScorePanel(true)
            }}>
            配置模板
          </Button>
        </Flex>
      </Flex>
      <Flex style={{ width: '100%', height: '100%' }}>
        <div className="meeting-content">{InterviewList()}</div>
      </Flex>
      {userDrawer()}
      {ScorePanelDrawer()}
    </div>
  )
}
